package com.flitsneak.rabbit.config;

import com.flitsneak.common.entity.Messages;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/8/8 9:06
 * @description rabbitmq 初始化
 */
@Slf4j
@Configuration
public class MQConfig {
    private static final String TOPIC_EXCHANGE = "order-event-exchange";

    private static final String DELAY_QUEUE = "order.delay.queue";

    private static final String RELEASE_QUEUE = "order.release.order.queue";

    private static final String ORDER_RELEASE = "order.release.order";

    private static final String ORDER_CREATE = "order.create.order";

    @Bean
    public Queue orderDelayQueue() {
        Map<String,Object> arguments = new HashMap<>(4);
        arguments.put("x-dead-letter-exchange",TOPIC_EXCHANGE);
        arguments.put("x-dead-letter-routing-key",ORDER_RELEASE);
        arguments.put("x-message-ttl",60000);

        return new Queue(DELAY_QUEUE, true, false, false, arguments);
    }

    @Bean
    public Queue orderReleaseOrderQueue() {
        return new Queue(RELEASE_QUEUE,true,false,false);
    }

    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange(TOPIC_EXCHANGE,true,false);
    }

    @Bean
    public Binding orderCreateOrderBinding() {
        return new Binding(DELAY_QUEUE, Binding.DestinationType.QUEUE,TOPIC_EXCHANGE,ORDER_CREATE,null);
    }

    @Bean
    public Binding orderReleaseOrderBinding() {
        return new Binding(RELEASE_QUEUE, Binding.DestinationType.QUEUE,TOPIC_EXCHANGE,ORDER_RELEASE,null);
    }

    /**
     * 注册监听器，接收过期消息
     * @param message 元消息信息
     * @param messages 自定义消息
     * @param channel 管道
     * @throws IOException 异常信息
     */
    @RabbitListener(queues = RELEASE_QUEUE)
    public void listener(Message message, Messages messages, Channel channel) throws IOException {
        log.info("收到过期order:{}",messages);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
